package com.bsg.upm.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.dto.DictTypeDto;
import com.bsg.upm.entity.DictTypeEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * 字典类型业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class DictTypeService extends BaseService {

	/**
	 * 字典类型查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			JSONArray results = new JSONArray();

			// 获取符合条件的字典类型
			List<DictTypeEntity> dictTypes = match(dictTypeCache.listDictTypeFromCache(), paramMap);
			for (DictTypeEntity dictType : dictTypes) {
				DictTypeDto dto = new DictTypeDto();
				dto.setCode(dictType.getCode());
				dto.setName(dictType.getName());
				results.add(dto);
			}
			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("字典类型查询异常", e);
			throw new APIException("字典类型查询异常:" + e.getMessage());
		}
	}

	/**
	 * 从指定的字典类型集合中匹配出符合条件的字典类型集合
	 * 
	 * @param dictTypes
	 *            字典类型集合
	 * @param paramMap
	 *            请求参数
	 * @return 符合条件的字典类型集合
	 */
	private List<DictTypeEntity> match(List<DictTypeEntity> dictTypes, Map<String, Object> paramMap) {
		List<DictTypeEntity> list = new ArrayList<>();
		for (DictTypeEntity dictType : dictTypes) {
			String code = (String) paramMap.get("code");
			String name = (String) paramMap.get("name");
			if (StringUtils.isNotBlank(code)) {
				if (!dictType.getCode().equals(code)) {
					continue;
				}
			}

			if (StringUtils.isNotBlank(name)) {
				if (!dictType.getName().contains(name)) {
					continue;
				}
			}
			list.add(dictType);
		}
		return list;
	}
}
